<template>
  <el-card>
    <el-form :model="listQuery" inline @submit.native.prevent>
      <el-form-item>
        <el-input
          v-model="listQuery.username"
          placeholder="按账号查找"
          clearable
          @keyup.enter.native="handleFilter"
        />
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="listQuery.nickname"
          placeholder="按姓名查找"
          clearable
          @keyup.enter.native="handleFilter"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleFilter">
          搜索
        </el-button>
      </el-form-item>
      <el-form-item style="float: right">
        <el-button v-has-perm="['user:add']" type="primary" icon="el-icon-plus" @click="handleCreate">
          新增
        </el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="listLoading" :data="list" highlight-current-row>
      <el-table-column
        label="序号"
        align="center"
        type="index"
        width="60"
        :index="(listQuery.pageIndex - 1) * listQuery.pageSize + 1"
      />
      <el-table-column label="账号" align="center" prop="username" />
      <el-table-column label="姓名" align="center" prop="nickname" />
      <el-table-column label="手机" align="center" prop="phone" />
      <el-table-column label="邮箱" align="center" prop="email" />
      <el-table-column label="状态" align="center" prop="locked">
        <template v-slot="{row}">
          <el-tag :type="row.locked ? 'info' : 'success'">{{ row.locked ? "冻结" : "正常" }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" />
      <el-table-column label="操作" align="center">
        <template v-slot="{ row }">
          <el-button v-has-perm="['user:edit']" size="mini" type="text" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-has-perm="['user:delete']" size="mini" type="text" @click="handleDelete(row.userId)">
            删除
          </el-button>
          <el-button v-has-perm="['user:reset']" size="mini" type="text" @click="resetPwd(row)">
            重置密码
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.pageIndex"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogVisible" width="500px" :close-on-click-modal="false">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="50px"
        v-loading="dialogLoading"
      >
        <el-form-item label="账号" prop="username">
          <el-input v-model="temp.username" placeholder="账号" />
        </el-form-item>
        <el-form-item label="姓名" prop="nickname">
          <el-input v-model="temp.nickname" placeholder="姓名" />
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="temp.phone" placeholder="手机" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="temp.email" placeholder="邮箱" />
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <el-select v-model="temp.roleIds" multiple filterable collapse-tags placeholder="选择角色" style="width: 410px">
            <el-option
              v-for="item in roles"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId"
            >
              <span style="float: left">{{ item.roleName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.roleKey }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="冻结" prop="locked">
          <el-switch v-model="temp.locked" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import Pagination from "@/components/Pagination/index"
import UserApi from "@/api/UserApi"
import RoleApi from "@/api/RoleApi"

export default {
  name: "UserPage",
  components: { Pagination },
  data() {
    return {
      list: [],
      roles: [],
      total: 0,
      listLoading: true,
      dialogLoading: false,
      listQuery: {
        pageIndex: 1,
        pageSize: 10
      },
      textMap: {
        update: "编辑",
        create: "新增"
      },
      rules: {
        username: [{ required: true, message: "请输入账号！", trigger: "blur" }]
      },
      dialogStatus: "",
      temp: {},
      dialogVisible: false
    }
  },
  created() {
    this.getRoleList()
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      UserApi.page(this.listQuery).then(result => {
        this.list = result.data
        this.total = result.total
        this.listLoading = false
      })
    },
    getRoleList() {
      RoleApi.list().then(result => {
        this.roles = result.data
      })
    },
    getCheckedRoles() {
      this.dialogLoading = true
      UserApi.getRoles(this.temp.userId).then(result => {
        this.$set(this.temp, "roleIds", result.data)
      }).finally(() => this.dialogLoading = false)
    },
    resetTemp() {
      this.temp = {
        name: undefined
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = "create"
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate()
      })
    },
    createData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          UserApi.save(this.temp).then(() => {
            this.$message.success("添加成功！")
            this.getList()
            this.dialogVisible = false
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = "update"
      this.dialogVisible = true
      this.$nextTick(() => {
        this.getCheckedRoles()
        this.$refs["dataForm"].clearValidate()
      })
    },
    updateData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          UserApi.update(this.temp).then(() => {
            this.dialogVisible = false
            this.getList()
            this.$message.success("修改成功！")
          })
        }
      })
    },
    handleDelete(id) {
      this.$confirm("此操作将永久删除该记录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        UserApi.delete(id).then(() => {
          this.dialogVisible = false
          this.getList()
          this.$message.success("操作成功！")
        })
      })
    },
    resetPwd(row) {
      this.$confirm("此操作将重置该账号密码, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        UserApi.resetPwd(row).then(() => {
          this.$message.success("操作成功！密码已重置为123456")
        })
      })
    },
    handleFilter() {
      this.listQuery.pageIndex = 1
      this.getList()
    }
  }
}
</script>
